package com.peanutplan.blog.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.peanutplan.blog.dao.SensitiveWordMapper;
import com.peanutplan.blog.model.vo.SensitiveWord;

/**
 * 敏感词工具，用来缓存和替换
 * @author motisy
 *
 */
@Component
public class SensitiveWordUtil implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(SensitiveWordUtil.class);

    
	@Autowired
	private SensitiveWordMapper mapper;
	
	private static Map<String, String> sensitiveWord_cache = new HashMap<String, String>();

	@Override
	public void run(String... args) throws Exception {
		LOGGER.info("初始化敏感词缓存......");
		List<SensitiveWord> all = mapper.selectByExample(null);
		
		for(int i=0; i<all.size(); i++) {
			SensitiveWord s = all.get(i);
			sensitiveWord_cache.put(s.getSensitiveWord(), s.getReplaceWord());
		}
		LOGGER.info("敏感词缓存完成，共初始化【"+sensitiveWord_cache.size()+"】个敏感词");
	}
	
	public void removeSensitiveWordCache(String ...sensitiveWords) {
		for(String i: sensitiveWords) {
			sensitiveWord_cache.remove(i);
			LOGGER.info("移出敏感词"+i);
		}
	}
	
	public void addSensitiveWordCache(SensitiveWord ...sensitiveWords) {
		for(SensitiveWord i: sensitiveWords) {
			sensitiveWord_cache.put(i.getSensitiveWord(), i.getReplaceWord());
			LOGGER.info("添加敏感词  "+i.getSensitiveWord()+"："+i.getReplaceWord());
		}
	}
	
	public String replaceSensitiveWord(String content) {
		if(StringUtils.isNotBlank(content)) {
			Set<Entry<String, String>> es = sensitiveWord_cache.entrySet();
			for(Entry<String, String> entry:es) {
				content = content.replaceAll(entry.getKey(), entry.getValue());
			}
		}
		return content;
	}
	
}
